/** @type {import('vite').UserConfig} */
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import { defineConfig, loadEnv } from 'vite'
import eslintPlugin from 'vite-plugin-eslint'
import moment from 'dayjs'
import viteCompression from 'vite-plugin-compression'

const path = require('path')
const formatTime = moment().format('YYYYMMDD_HHmmss')

// 配置 按需导入-> 自动导入
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { VueUseComponentsResolver, TDesignResolver } from 'unplugin-vue-components/resolvers'

// https://vitejs.dev/config/
export default ({ mode }) => {
  return defineConfig({
    server: {
      // open: true, //启动项目自动弹出浏览器
      // port: 4000, //启动端口
      proxy: {
        '^/api': {
          target: loadEnv(mode, process.cwd()).VITE_BASE_URL,
          // target: 'http://localhost:8000',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/api/, '')
        },
        '^/test': {
          target: loadEnv(mode, process.cwd()).VITE_TEST_URL,
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/test/, '')
        }
      }
    },
    plugins: [
      vue(),
      vueJsx(),
      // splitVendorChunkPlugin(),
      AutoImport({
        // 目标文件
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/, /\.vue\?vue/, // .vue
          /\.md$/, // .md
        ],
        resolvers: [
          VueUseComponentsResolver(),
          TDesignResolver({
            library: 'vue-next'
          })],
        // 全局引入插件
        imports: [
          // presets
          'vue',
          'vue-router',
          // custom
          {
            '@vueuse/core': [
              // named imports
              'useMouse', // import { useMouse } from '@vueuse/core',
              // alias
              ['useFetch', 'useMyFetch'], // import { useFetch as useMyFetch } from '@vueuse/core',
            ],
            'axios': [
              // default imports
              ['default', 'axios'], // import { default as axios } from 'axios',
            ],
            '[package-name]': [
              '[import-names]',
              // alias
              ['[from]', '[alias]'],
            ],
          },
        ],
        // eslint报错解决
        eslintrc: {
          enabled: false, // Default `false`
          filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
          globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
        },
        // 声明文件生成位置和文件名称
        dts: './auto-import.d.ts'
      }),
      Components({
        dirs: ['src/components', 'src/views'],// 自动导入组件的项目目录
        resolvers: [
          VueUseComponentsResolver(),
          IconsResolver(),
          TDesignResolver({
            library: 'vue-next'
          })]
      }),
      Icons({
        /* options */
        autoInstall: true,
      }),
      eslintPlugin({
        include: ['src/**/*.js', 'src/**/*.vue', 'src/*.js', 'src/*.vue', 'src/*.jsx']
      }),
      viteCompression()
    ],
    build: {
      target: 'esnext',
      minify: 'terser',
      reportCompressedSize: true,
      terserOptions: {
        compress: {
          //生产环境时移除console
          drop_console: true,
          drop_debugger: true,
        },
      },
      rollupOptions: {
        output: {
          // 用于从入口点创建的块的打包输出格式[name]表示文件名
          entryFileNames: `js/[name].${formatTime}.js`, // 用时间戳代替hash，一看源码就知道代码是什么时候上传的，清晰明了，避免扯皮~
          // 用于命名代码拆分时创建的共享块的输出命名
          chunkFileNames: `js/[name].${formatTime}.js`,
          // 用于输出静态资源的命名，把css剥离出来，剩下资源还在static中
          //assetFileNames: `css/[name].${formatTime}.css`, // 或者用下面的写法↓↓↓
          // 静态资源以扩展名来拆分目录（[ext]表示文件扩展名）
          assetFileNames: `[ext]/[name]-${formatTime}.[ext]`, // 打包后的目录中可能会出现png、jpg、svg、ttf、gif等目录。
          manualChunks: {
            vue: ['vue'],
            'vue-router': ['vue-router'],
            axios: ['axios'],
            pinia: ['pinia'],
            // 'tdesign-vue-next': ['tdesign-vue-next'],
          }
        }
      }
    },
    // 别名
    resolve: {
      alias: {
        //设置别名
        '@': path.resolve(__dirname, './src'),
        '@assets': path.resolve(__dirname, './src/assets')
      },
      extensions: ['.js', '.jsx', '.ts', '.tsx', '.vue', '.json']
    },
    // 导入全局less变量
    css: {
      preprocessorOptions: {

        less: {

          modifyVars: {

            hack: `true; @import (reference) "${path.resolve('src/assets/main.less')}";`,
          },
          javascriptEnabled: true
        }
      }
    },
  })
}